#include "StatusBar.h"
#include <core/StyleMgr.h>
#include <widgets/SImageButton.h>
#include <widgets/SButtonTips.h>
#include <widgets/cefview/CefViewWidget.h>
#include <guiframe/IApplication.h>
#include <qbkernel/include/qb_base.h>
#include <QRandomGenerator>
#include <QMenu>
#include "../login/auth_login.h"
#include "status/AccountInfo.h"
#include "status/AboutDlg.h"
#include "status/MobileDlg.h"
#include "MobileConfirmDlg.h"
#include <bondlib/Pinyin.h>
#include <uam/UserAccountManager.h>
#include <include/NameDefines.h>


namespace {
	int randInt(int mi, int mx) {
		return QRandomGenerator::global()->bounded(mi, mx + 1);
	}

	enum
	{
		//eFT_PL_SYS_TIME = 6025,
		eFT_PL_FORCE_QUIT = 6028,
		eFT_PL_HEART_BREAK_SYS_OK = 6030,
		eFT_PL_HEART_BREAK_SYS_NOK = 6031,
		//eFT_PL_HEART_RECONN_SYS_ING = 6032,
		//eFT_PL_HEART_BREAK_SYS_OK2 = 6036,
	};
}

StatusBarWorker::~StatusBarWorker()
{
	qb::qbBase::getNetworkService()->DeRegisterNetworkEventObserver(this);
}

void StatusBarWorker::onReady(QWidget* pp)
{
	m_pStatusbar = pp;
	//网络状状态
	IMainFrame* pFrame = sApp->mainFrame();
/*	m_btnNetState = new SImageButton(pp, "guiframe_state_online");
	pFrame->addStatusbarItem(m_btnNetState);

	//帮助中心
	SImageButton* btnHelp = new SImageButton(pp, "guiframe_button_help");
	btnHelp->setToolTip("帮助中心");
	btnHelp->setColor(NAME_COLOR("MainTitleBack"), NAME_COLOR("Hover"), NAME_COLOR("Hover"), NAME_COLOR("MainTitleBack"));
	btnHelp->setFixedSize(24, 24);
	pFrame->addStatusbarItem(btnHelp);
	connect(btnHelp, &SImageButton::clicked, this, &StatusBarWorker::onHelpClicked);

	//消息中心
	m_btnMsgCenter = new SImageButton(pp, "guiframe_app_sound");
	m_btnMsgCenter->setToolTip("消息中心");
	m_btnMsgCenter->setColor(NAME_COLOR("MainTitleBack"), NAME_COLOR("Hover"), NAME_COLOR("Hover"), NAME_COLOR("MainTitleBack"));
	m_btnMsgCenter->setFixedSize(24, 24);
	pFrame->addStatusbarItem(m_btnMsgCenter);
	connect(m_btnMsgCenter, &SImageButton::clicked, this, &StatusBarWorker::onMsgCenterClicked);

	//服务平台
	SImageButton* btnService = new SImageButton(pp, "guiframe_app_manager");
	btnService->setToolTip("服务平台");
	btnService->setColor(NAME_COLOR("MainTitleBack"), NAME_COLOR("Hover"), NAME_COLOR("Hover"), NAME_COLOR("MainTitleBack"));
	btnService->setFixedSize(24, 24);
	pFrame->addStatusbarItem(btnService);
	connect(btnService, &SImageButton::clicked, this, &StatusBarWorker::onServiceClicked);

	//账号信息
	static QColor accountBkg[12] = { 0xbf3532, 0xc6532d, 0xc97e33, 0xcd9838, 0xd3bd42, 0x96b93c, 0x67a738, 0x51a6a7, 0x3e7dd5, 0x324cc4, 0x5c32ae, 0xb93c81 };
	QColor bk = accountBkg[randInt(0, 11)];
	QString* fmt = new QString("QPushButton{background-color:#%1; border-radius:5px;}");
    m_btnAccountInfo = new QPushButton(pp);
    m_btnAccountInfo->setObjectName(kAccountInfo); // need a name for webFunc
	m_btnAccountInfo->setToolTip("账号信息");
	m_btnAccountInfo->setStyleSheet(fmt->arg(bk.rgb(), 0, 16));
	m_btnAccountInfo->setFixedSize(24, 24);
	pFrame->addStatusbarItem(m_btnAccountInfo);
	connect(m_btnAccountInfo, &QPushButton::clicked, this, &StatusBarWorker::onAccountInfoClicked);
	setUserName();*/

    m_btnAccountInfo = new QPushButton(pp);
    m_btnAccountInfo->setObjectName(kAccountInfo); // need a name for webFunc
    m_btnAccountInfo->setToolTip("账号信息");
    m_btnAccountInfo->setFixedSize(24, 24);
    // hide -- for internal use only
    m_btnAccountInfo->hide();
    pFrame->addStatusbarItem(m_btnAccountInfo);
    connect(m_btnAccountInfo, &QPushButton::clicked, this, &StatusBarWorker::onAccountInfoClicked);

	QString* fmt = new QString("QPushButton{background-color:#%1; color:#%2}");
	m_btnAccountInfo = new QPushButton(tr("欢迎您"), pp);
	m_btnAccountInfo->setObjectName(kAccountInfo);
	m_btnAccountInfo->setStyleSheet(fmt->arg(StyleMgr::instance().color("MainTitleBack").rgb(), 0, 16).arg(StyleMgr::instance().color("LabelNormal").rgb(), 0, 16));
	m_btnAccountInfo->setFixedSize(36, 24);
	m_btnAccountInfo->setEnabled(false);
	pFrame->addStatusbarItem(m_btnAccountInfo);

	//设置
	QString name = QString::fromUtf8(SSUserAccountManager::instance().GetUserInfo().m_DisplayName_Utf8);
	if (name.isEmpty()) {
		name = QString::fromUtf8(SSUserAccountManager::instance().GetUserAccount());
	}

	m_btnSetting = new SImageButton(pp, "guiframe_dropdown_down", "", name);
	m_btnSetting->setToolTip("设置");
	m_btnSetting->setColor(NAME_COLOR("MainTitleBack"), NAME_COLOR("Hover"), NAME_COLOR("Hover"), NAME_COLOR("MainTitleBack"));
	m_btnSetting->setFixedSize(m_btnSetting->getIconTextLength() + 24, 24);
	pFrame->addStatusbarItem(m_btnSetting);
	connect(m_btnSetting, &SImageButton::clicked, this, &StatusBarWorker::onSettingClicked);

	qb::qbBase::getNetworkService()->RegisterNetworkEventObserver(this);
//	connect(this, SIGNAL(networkStateChanged(int)), this, SLOT(setNetworkState(int)));
//	connect(this, &StatusBarWorker::userInfoReady, this, &StatusBarWorker::setUserName);
}

void StatusBarWorker::onUserInfoReady()
{
	emit userInfoReady();
}

void StatusBarWorker::setUserName()
{
	qb::PinyinManager& pyMgr = qb::PinyinManager::instance();
	QString name = QString::fromUtf8(SSUserAccountManager::instance().GetUserInfo().m_DisplayName_Utf8);
	if (name.isEmpty()) {
		name = QString::fromUtf8(SSUserAccountManager::instance().GetUserAccount());
	}
//	std::string py = pyMgr.GetPinyin(name.toLocal8Bit());
//	if (py.empty()) {
//		py = "S";
//	}

	m_btnAccountInfo->setText(name);
}

void StatusBarWorker::onHelpClicked()
{
}

void StatusBarWorker::onMsgCenterClicked()
{
	if (m_msgCount > 0) {
		m_msgCount -= 1;
	}
}

void StatusBarWorker::onServiceClicked()
{
}

void StatusBarWorker::onAccountInfoClicked()
{
    AccountInfo dlg;
    if (QObject* _sender = this->sender() ) {
        const QString senderName = _sender->objectName();
        if (senderName.startsWith(kAccountInfo)) {
            const QString select = senderName.mid(strlen(kAccountInfo));
            connect(&dlg, &AccountInfo::showup, [&dlg, select](){
                dlg.SetPanelSelect(select);
            });
        }
    }

	dlg.exec();
}

void StatusBarWorker::onSettingClicked()
{
	QMenu* menu = new QMenu();
	QAction* aAccountInfo = new QAction(tr("账号信息"), this);
	menu->addAction(aAccountInfo);
	menu->addSeparator();
	QAction* aboutQB = new QAction(tr("关于qeubee"), this);
	menu->addAction(aboutQB);
	menu->addSeparator();
	QAction* mobileQB = new QAction(tr("手机qeubee"));
	menu->addAction(mobileQB);
	menu->addSeparator();

	QAction* mobileConfirm = new QAction(tr("手机验证"));
	menu->addAction(mobileConfirm);

    QAction* aboutUS = new QAction(tr("关于我们"));
    menu->addAction(aboutUS);

	menu->addSeparator();
	QAction* logout = new QAction(tr("注销登录"));
	menu->addAction(logout);
	menu->setDefaultAction(logout);

	connect(aAccountInfo, &QAction::triggered, this, &StatusBarWorker::onAccountInfoClicked);
	connect(aboutQB, &QAction::triggered, this, &StatusBarWorker::onMenuAboutQB);
	connect(mobileQB, &QAction::triggered, this, &StatusBarWorker::onMenuMobileQB);
	connect(mobileConfirm, &QAction::triggered, this, &StatusBarWorker::onMenuMobileConfirm);
    connect(aboutUS, &QAction::triggered, this, &StatusBarWorker::onMenuAboutUS);
	connect(logout, &QAction::triggered, this, &StatusBarWorker::onMenuLogout);

	menu->setStyleSheet(QString(
		"QMenu::item {padding:6px 38px 6px 18px;}\n"
		"QMenu::item:hover {background-color:#%2;}\n"
		"QMenu::item:disabled {color:#%3;}\n"
		"QMenu {background-color:#%4; margin:0px;font:12px Microsoft YaHei;font-weight:bold;}\n"
		"QMenu::separator{height:1px; background:#%5; margin-left:0px; margin-right:0px;}\n"
		"QMenu::item:default { color: #%6; }")
		.arg(NAME_COLOR("Hover").rgb(), 0, 16)
		.arg(NAME_COLOR("SupportingWord").rgb(), 0, 16)
		.arg(NAME_COLOR("ElementBackground").rgb(), 0, 16)
		.arg(NAME_COLOR("PartPlate").rgb(), 0, 16)
		.arg(NAME_COLOR("Up_Increase_H1").rgb(), 0, 16));
	menu->exec(QCursor::pos());
}

void StatusBarWorker::onMenuAboutQB()
{
	AboutDlg dlg;
	dlg.exec();
}

void StatusBarWorker::onMenuMobileQB()
{
	MobileDlg dlg;
	dlg.exec();
}

void StatusBarWorker::onMenuExcelPlugin()
{
}

void StatusBarWorker::onMenuSysSetting()
{
}

void StatusBarWorker::onMenuMobileConfirm()
{
	AccountInfo dlg;
	dlg.exec();
}

void StatusBarWorker::onMenuAboutUS()
{
    SPopupWindow aboutUs;
    aboutUs.setTitle(tr("关于我们"));
    QVBoxLayout* layout = aboutUs.contentLayout();
    //"WEB_ABOUTUS"
    CefViewWidget* cef=new CefViewWidget("https://qbweb.idbhost.com/basehtml/mobile/app/aboutUs.html", nullptr, &aboutUs);
    cef->setFixedSize(622, 668);
    layout->addWidget(cef);

    aboutUs.exec();
}

void StatusBarWorker::onMenuLogout()
{
}


void StatusBarWorker::moveBtnTips() {
	if (m_btnNetState != nullptr
		&& m_btnReconnectTips != nullptr)
	{
		QRect rc = m_btnNetState->rect();
		QPoint pt = m_btnNetState->mapToGlobal(QPoint(rc.left() + rc.width() / 2, rc.bottom()));
		pt.setX(pt.x() - m_btnReconnectTips->width() + 20);
		pt.setY(pt.y() + 5);
		m_btnReconnectTips->move(pt);
	}
}

STDMETHODIMP_(void) StatusBarWorker::OnForceQuit(THIS_ int32_t connect_id)
{
	emit networkStateChanged(eFT_PL_FORCE_QUIT);
}

STDMETHODIMP_(void) StatusBarWorker::OnDisConnect(THIS_ int32_t connect_id)
{
	emit networkStateChanged(eFT_PL_HEART_BREAK_SYS_NOK);
}

STDMETHODIMP_(void) StatusBarWorker::OnRecover(THIS_ int32_t connect_id)
{
	emit networkStateChanged(eFT_PL_HEART_BREAK_SYS_OK);
}

void StatusBarWorker::setNetworkState(int state)
{
	m_networkState = state;

	//刷新网络状态
	switch (state)
	{
	case eFT_PL_HEART_BREAK_SYS_OK://连接成功
		m_netOK = true;
		updateNetStatus();
		break;
	case eFT_PL_HEART_BREAK_SYS_NOK://连接失败
	case eFT_PL_FORCE_QUIT:
		m_netOK = false;
		updateNetStatus();
		break;
	default:
		break;
	}

	//显示/隐藏断网后提示窗口
	if (state == eFT_PL_HEART_BREAK_SYS_OK)
	{
		hideReconnectTips();
	}
	else if (state == eFT_PL_HEART_BREAK_SYS_NOK)
	{
		showReconnectTips();
	}
}

void StatusBarWorker::updateNetStatus()
{
	if (m_btnNetState != nullptr)
	{
		m_btnNetState->setImgId(m_netOK ?
			"guiframe_state_online" :
			"guiframe_state_offline");
		m_btnNetState->update();
	}
}

void StatusBarWorker::showReconnectTips()
{
	if (m_btnReconnectTips == nullptr)
	{
		m_btnReconnectTips = new SButtonTips(m_pStatusbar);
		connect(m_btnReconnectTips, &SButtonTips::onButtonClicked, this, &StatusBarWorker::onReconnectNetwork);
	}

	moveBtnTips();

	m_btnReconnectTips->raise();
	if (!m_btnReconnectTips->isVisible())
	{
		m_btnReconnectTips->show();
	}
	m_btnReconnectTips->setLabelText("服务器连接失败！联系客服400-119-9898");
	m_btnReconnectTips->setButtonText("重试");
	m_btnReconnectTips->setButtonVisible(true);
	m_btnReconnectTips->setButtonColor(NAME_COLOR("BasicBtn_Filter_Tittle"), NAME_COLOR("TextNormal"));
	m_btnReconnectTips->setFixedWidth(415);
}

void StatusBarWorker::hideReconnectTips()
{
	if (m_btnReconnectTips != nullptr
		&& m_btnReconnectTips->isVisible())
	{
		m_btnReconnectTips->hide();
	}
}

void StatusBarWorker::onReconnectNetwork() {
	m_btnReconnectTips->setLabelText("无法连接服务器！正在尝试重新连接...");
	m_btnReconnectTips->setButtonVisible(false);
	m_btnReconnectTips->setFixedWidth(300);
	qb::CAuthLogin::instance().manualReLogin();
}
